package com.chukun.spring.beans.defination;


import com.chukun.spring.beans.factory.DefaultUserFactory;
import com.chukun.spring.beans.factory.UserFactory;
import com.chunkun.ioc.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * @author chukun
 *  特殊的实例化bean的方式
 */
public class SpecialBeanInstantiationDemo {

    public static void main(String[] args) {

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/META-INF/special-bean-instantiation-context.xml");

        // 获取AutowireCapableBeanFactory
        AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();

        // 通过ServiceLoaderFactoryBean创建对象
        ServiceLoader<UserFactory> serviceLoader = beanFactory.getBean("userFactoryServiceLoader", ServiceLoader.class);

        // serviceLoaderBean();

        // displayServiceLoader(serviceLoader);

        // 创建userFactory 通过AutowireCapableBeanFactory
        UserFactory userFactory = beanFactory.createBean(DefaultUserFactory.class);
        System.out.println(userFactory.createUser());

    }

    /**
     * 使用serviceLoader创建对象
     *
     * 1. 在 classpath下的 META-INF/services,创建工厂的文件
     * 2、文件里面写工厂的实现类
     */
    public static void serviceLoaderBean() {
        ServiceLoader<UserFactory> load = ServiceLoader.load(UserFactory.class, Thread.currentThread().getContextClassLoader());
        Iterator<UserFactory> iterator = load.iterator();
        while (iterator.hasNext()) {
            UserFactory userFactory = iterator.next();
            System.out.println(userFactory.createUser());
        }
    }

    /**
     * 展示所有的bean
     * @param serviceLoader
     */
    public static void displayServiceLoader(ServiceLoader<UserFactory> serviceLoader) {
        Iterator iterator = serviceLoader.iterator();
        while (iterator.hasNext()) {
            UserFactory userFactory = (UserFactory) iterator.next();
            System.out.println(userFactory.createUser());
        }
    }
}
